<template>
  <div class="update-name">
    <van-nav-bar
      title="修改昵称"
      left-text="取消"
      right-text="完成"
      @click-left="$emit('close')"
      @click-right="onConfirm"
    />
    <div class="name-field-wrap">
      <van-field
        v-model="localName"
        rows="2"
        autosize
        type="textarea"
        maxlength="7"
        placeholder="请输入昵称"
        show-word-limit
      />
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  components: {},
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      localName: this.value
    }
  },
  computed: {
    ...mapState(['user'])
  },
  watch: {},
  created () {},
  mounted () {},
  methods: {
    async onConfirm () {
      this.$toast.loading({
        message: '保存中',
        forbidclick: true
      })
      await this.$http.put('api/user/logoInfo', {
        data: {
          nickname: this.localName,
          username: this.user.username
        }
      }).then(({ data: res }) => {
        if (res.code === 0) {
          const data = {
            ...this.user,
            nickname: this.localName
          }
          this.$emit('input', this.localName)
          this.$emit('close')
          this.$store.commit('setUser', data)
          this.$toast.success('保存成功')
        } else {
          this.$toast.fail('修改失败')
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
.name-field-wrap {
  padding: 10px;
}
</style>
